//
//  GroupChatPacketCenter.m
//  HiQServer
//
//  Created by arvintan on 12-8-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "GroupChatPacketCenter.h"
#import "SockPacket.h"
#import "MiniSocket.h"
#import "MainSocketDelegate.h"
#import "MacroComd.h"
#import "MysqlDB.h"

@implementation GroupChatPacketCenter

-(NSData*) msgCmd:(NSString *)msg cmd:(NSUInteger)cmdFlag subcmd:(NSUInteger)subCmdFlag
{
    NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger length = data.length + 16;
    NSLog(@"data length is %lu,%lu",data.length,sizeof(NSUInteger));
    NSMutableData *dataWithCmd = [NSMutableData dataWithBytes:&(length) length:sizeof(NSUInteger)];
    [dataWithCmd appendBytes:&(cmdFlag) length:sizeof(NSUInteger)];
    [dataWithCmd appendBytes:&(subCmdFlag) length:sizeof(NSUInteger)];
    [dataWithCmd appendData:data];
    
    return dataWithCmd;
}

-(void)MessageDispatch: (SockPacket *)packet
{
    UTF8Char * bytes = (UTF8Char *)[packet.packetContent bytes] + 8;
    NSUInteger subFun =*((NSUInteger *) bytes);
    switch (subFun)
    {
        case CMD_GROUPCHAT_SEND:
        {
            NSString *msg = [[NSString alloc] initWithBytes:(bytes+8)
                                                     length:(packet.packetLen-16) encoding:NSUTF8StringEncoding];
            if(msg)
            {
                MysqlDB *mysql = [[MysqlDB alloc] init];
                [mysql connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
                
                //包格式为  群号/发送方姓名/消息
                NSArray *msgArray = [msg componentsSeparatedByString:@"/"];
                NSUInteger groupId = (NSUInteger)[[msgArray objectAtIndex:0] intValue];
                NSUInteger userId = (NSUInteger)[[msgArray objectAtIndex:2] intValue];
                
                NSString *sqlCluster = [NSString stringWithFormat:@"select MemberId from tbGroupMember where GroupId = %ld",groupId];
                NSMutableArray *memberIDResult = [mysql doDataQuery:sqlCluster];
                
                for (NSUInteger i = 0; i < [memberIDResult count]; ++i) {
                    NSArray *idInfo =[memberIDResult objectAtIndex:i];
                    NSInteger memberId = [[idInfo objectAtIndex:0] integerValue];
                    if(memberId != userId)
                    {
                        @synchronized([MainSocketDelegate connectedSocketsQueue])
                        {
                            MiniSocket *_sock = [self isBuddyOnline:memberId];   // 判断该好友是否在线
                            if (_sock != nil)
                            {
                                NSData *sendData = [self msgCmd:msg cmd:CMD_FUN_GROUPCHAT subcmd:CMD_GROUPCHAT_RECEIVE];
                                [_sock.miniAsynSocket writeData:sendData withTimeout:-1 tag:0];
                            }
                        }
                    }
                    
                }
                [mysql disconnect];
            
            }
            else
            {
                NSLog(@"Error converting received data into UTF-8 String");
            }
            break;
        }
        case 1:
            
            break;
        default:
            break;
    }
    
}

// 判断 userId 对应的用户是否在线
- (MiniSocket *)isBuddyOnline:(NSInteger)userId
{
    @synchronized([MainSocketDelegate connectedSocketsQueue])
    {
        // 遍历 connectedSocketQueue，找到该好友的 _sock
        for (MiniSocket *_sock in [MainSocketDelegate connectedSocketsQueue]) 
        {
            if (_sock.userId == userId)
            {
                return _sock;
            }
        }
        return nil;
    }
}

@end
